﻿using Audit.Core;
using Dapper_Core.BLL.Interface;
using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using ExpressionToWhere;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Dapper_Core.BLL.Impl
{
    public class Sys_User_RoleBusiness : BaseRepository<Sys_User_Role>, ISys_User_RoleBusiness
    {
        public Sys_User_RoleBusiness()
        {

        }

        public Sys_User_RoleBusiness(TransactionContext transactionContext) : base(transactionContext)
        {

        }

        public bool UpdateRelation(string addRoleCodes, string deleteRoleCodes, string userCode, string creator)
        {
            TransactionContext transactionContext = null;
            try
            {
                if (string.IsNullOrEmpty(addRoleCodes) && string.IsNullOrEmpty(deleteRoleCodes)) return true;
                if (string.IsNullOrEmpty(userCode)) return true;
                List<string> addRoleList = (addRoleCodes ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                List<string> deleteRoleList = (deleteRoleCodes ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                if (addRoleList.Count < 1 && deleteRoleList.Count < 1) return true;
                List<Sys_User_Role> userRoleList = new List<Sys_User_Role>();
                DateTime createDate = DateTime.Now;
                foreach (string roleCode in addRoleList)
                {
                    Sys_User_Role userRole = new Sys_User_Role();
                    userRole.Id = Guid.NewGuid().ToString();
                    userRole.UserCode = userCode;
                    userRole.RoleCode = roleCode;
                    userRole.Creator = creator;
                    userRole.CreateDate = createDate;
                    userRoleList.Add(userRole);
                }

                transactionContext = InitialTransaction();
                //开启事务
                transactionContext.BeginTransaction();
                if (deleteRoleList.Count > 0)
                {
                    Expression<Func<Sys_User_Role, bool>> exp = userRole => userRole.UserCode == userCode && userRole.RoleCode.In(deleteRoleList);
                    base.DeleteList(exp);
                }
                base.AddList(userRoleList);
                //记录审计日志
                using (AuditScope scope = AuditScope.Create("Sys_User_Role:Update", () => new { userCode = userCode, addRoleCodes = addRoleCodes, deleteRoleCodes = deleteRoleCodes }))
                {
                    scope.Comment("更新“用户 - 系统角色”对应关系");
                    scope.SetCustomField("Module", "Sys_User_Role");
                    scope.SetCustomField("Operator", creator);
                    scope.SetCustomField("Operation", Operation.Update);
                }
                //提交事务
                transactionContext.Commit();
                return true;
            }
            catch (Exception ex)
            {
                //回滚事务
                transactionContext.Rollback();
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "更新“用户 - 系统角色”对应关系失败", "addRoleCodes=" + addRoleCodes + "，deleteRoleCodes=" + deleteRoleCodes + "，userCode=" + userCode + "，creator=" + creator, ex, "DapperCore");
                return false;
            }
        }

        public List<V_Sys_UserRole> GetUsers(string roleCode, string deptId, string deptType, string applyMan)
        {
            try
            {
                List<V_Sys_UserRole> userRoleList = new List<V_Sys_UserRole>();
                if (roleCode == "ADMP_Flow_Submitter")
                {
                    userRoleList.Add(new V_Sys_UserRole() { RoleCode = "ADMP_Flow_Submitter", PinyinCode = applyMan });
                    return userRoleList;
                }
                else if (roleCode == "ADMP_Flow_DepartmentManager")
                {
                    if (deptType == "yanfa")
                    {
                        Sys_Department rdDepartment = new BaseRepository<Sys_Department>().Get(deptId);
                        userRoleList.Add(new V_Sys_UserRole() { RoleCode = "ADMP_Flow_DepartmentManager", PinyinCode = rdDepartment.DeptManager });
                    }
                    else
                    {
                        Sys_Department department = new BaseRepository<Sys_Department>().Get(deptId);
                        userRoleList.Add(new V_Sys_UserRole() { RoleCode = "ADMP_Flow_DepartmentManager", PinyinCode = department.DeptManager });
                    }
                    return userRoleList;
                }
                else
                {
                    Expression<Func<V_Sys_UserRole, bool>> exp = userRole => userRole.RoleCode == roleCode;
                    userRoleList = new BaseRepository<V_Sys_UserRole>().GetList(exp).ToList();
                }
                return userRoleList;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取下一步审批人失败", $"roleCode={roleCode}，deptId={deptId}，deptType={deptType}", ex, "DapperCore");
                return new List<V_Sys_UserRole>();
            }
        }
    }
}
